package net.esj.struts.components;

import java.io.IOException;
import java.io.Writer;

import net.esj.basic.utils.view.HtmlUtils;

import org.apache.log4j.Logger;
import org.apache.struts2.components.Component;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;

import com.opensymphony.xwork2.util.ValueStack;

@StrutsTag(name="textwrap", tldBodyContent="empty", tldTagClass="net.esj.struts.views.jsp.TextWrapTag",
	    description="Print out expression with word-wrapped")
public class TextWrap extends Component {
	
	protected static final Logger logger = Logger.getLogger(TextWrap.class);
	
	private String value;

	public TextWrap(ValueStack stack) {
		super(stack);
	}
	
    @StrutsTagAttribute(description="Value to be displayed", type="Object", defaultValue="&lt;top of stack&gt;")
    public void setValue(String value) {
        this.value = value;
    }

	public boolean start(Writer writer) {
        boolean result = super.start(writer);

        String actualValue = null;

        if (value == null) {
            value = "top";
        }
        else {
        	value = stripExpressionIfAltSyntax(value);
        }

        actualValue = (String) getStack().findValue(value, String.class, throwExceptionOnELFailure);

        try {
            if (actualValue != null) {
                writer.write(prepare(actualValue));
            }
        } catch (IOException e) {
        	logger.info("Could not print out value '" + value + "'", e);
        }

        return result;
    }
	
	private String prepare(String actvalue){
		String result = HtmlUtils.formateTextarea(actvalue);
		return result;
	}
}
